package com.yzt.zhuju.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Application;
import android.app.NotificationChannel;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationChannelCompat;
import androidx.core.app.NotificationManagerCompat;

import com.yzt.p_base.AppUtils;

import java.lang.reflect.Method;
import java.util.Locale;

/**
 * author : bob
 * date   : 2022/11/30
 * desc   :
 */
public class SystemUtil {

    private static String currentProcessName;

    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return 语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取设备AndroidID
     *
     * @param context 上下文
     * @return AndroidID
     */
    @SuppressLint("HardwareIds")
    public static String getAndroidID(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    /**
     * 判断通知权限是否打开
     */
    public static boolean isNotificationEnable() {
        NotificationManagerCompat manager = NotificationManagerCompat.from(AppUtils.getApp());
        return manager.areNotificationsEnabled();
    }

    /**
     *  判断通知开关是否打开了
     */
    public static boolean isNotificationEnable(@Nullable NotificationChannel defaultChannel) {
        if (defaultChannel == null) {
            return false;
        }
        if (!isNotificationEnable()) {
            return false;
        }
        NotificationManagerCompat manager = NotificationManagerCompat.from(AppUtils.getApp());
        NotificationChannelCompat notificationChannelCompat = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannelCompat = manager.getNotificationChannelCompat(defaultChannel.getId());
        }else{
            return false;
        }
        if (notificationChannelCompat != null) {
            int importance = notificationChannelCompat.getImportance();
            return importance != NotificationManagerCompat.IMPORTANCE_NONE;
        }else{
            return false;
        }
    }

    /**
     * 判断是否在主进程
     */
    public static boolean inMainProcess(Context context) {
        return isAppMainProcess(context);
    }

    private static boolean isAppMainProcess(Context context) {
        if (context == null) {
            return false;
        }

        String packageName = context.getApplicationContext().getPackageName();
        String processName = getProcessNamePure(context);
        if(TextUtils.isEmpty(processName))
        {
            return isAppMainProcessForPID(context);
        }
        return packageName.equals(processName);
    }

    /**
     * 通过Application新的API获取进程名，无需反射，无需IPC，效率最高。
     */
    private static String getCurrentProcessNameByApplication() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            return Application.getProcessName();
        }
        return null;
    }

    public static String getProcessNamePure(Context context) {
        if(!TextUtils.isEmpty(currentProcessName))
        {
            return currentProcessName;
        }
        currentProcessName = getCurrentProcessNameByApplication();
        if(!TextUtils.isEmpty(currentProcessName))
        {
            return currentProcessName;
        }

        currentProcessName = getCurrentProcessNameByActivityThread();

        TextUtils.isEmpty(currentProcessName);

        return currentProcessName;
    }

    /**
     * 判断是不是UI主进程，因为有些东西只能在UI主进程初始化
     */
    private static boolean isAppMainProcessForPID(Context context) {
        try {
            String packageName = context.getPackageName();
            int pid = android.os.Process.myPid();
            String process = getAppNameByPID(context, pid);
            if (TextUtils.isEmpty(process)) {
                return true;
            } else return packageName.equalsIgnoreCase(process);
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }
    /**
     * 根据Pid得到进程名
     */
    private static String getAppNameByPID(Context context, int pid) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (android.app.ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == pid) {
                return processInfo.processName;
            }
        }
        return "";
    }

    /**
     * 通过反射ActivityThread获取进程名，避免了ipc
     */
    private static String getCurrentProcessNameByActivityThread() {
        String processName = null;
        try {
            final Method declaredMethod = Class.forName("android.app.ActivityThread", false, Application.class.getClassLoader())
                    .getDeclaredMethod("currentProcessName", new Class[0]);
            declaredMethod.setAccessible(true);
            final Object invoke = declaredMethod.invoke(null);
            if (invoke instanceof String) {
                processName = (String) invoke;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return processName;
    }
}
